import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import matplotlib as mpl
from matplotlib.font_manager import FontProperties

# 设置图表样式
sns.set_style('whitegrid')
# 设置支持中文的字体
plt.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'SimHei', 'Microsoft YaHei', 
                                  'WenQuanYi Micro Hei', 'Heiti TC', 'STHeiti', 'AR PL UMing CN', 
                                  'AR PL UKai CN', 'STFangsong', 'DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False
plt.rcParams.update({'font.size': 12})

# 解决MacOS上中文显示问题的函数
def set_chinese_font():
    try:
        # 尝试使用以下字体
        for font in ['Arial Unicode MS', 'SimHei', 'Microsoft YaHei', 'SimSun']:
            try:
                chinese_font = FontProperties(fname=f'/System/Library/Fonts/STHeiti Light.ttc')
                return chinese_font
            except:
                continue
        # 如果上面的都失败，使用默认字体
        return FontProperties()
    except:
        return FontProperties()

chinese_font = set_chinese_font()

# 创建保存图表的目录
if not os.path.exists('figures'):
    os.makedirs('figures')

# 加载合成数据
df = pd.read_csv('data/synthetic_panel_data.csv')

# 1. 银行处罚趋势图 (2011-2020)
plt.figure(figsize=(10, 6))
yearly_penalties = df.groupby('year')['bank_penalty'].mean()
plt.plot(yearly_penalties.index, yearly_penalties.values, marker='o', linewidth=2, markersize=8)
plt.axvline(x=2015, color='r', linestyle='--', label='2015年政策变更')
plt.xlabel('年份', fontproperties=chinese_font)
plt.ylabel('平均银行处罚强度', fontproperties=chinese_font)
plt.title('银行监管处罚趋势 (2011-2020)', fontproperties=chinese_font)
plt.grid(True, alpha=0.3)
plt.legend(prop=chinese_font)
plt.tight_layout()
plt.savefig('figures/fig1_penalty_trends.png', dpi=300)

# 2. 企业融资比例随时间变化
plt.figure(figsize=(12, 7))
financing_ratios = df.groupby('year')[['debt_ratio', 'equity_ratio', 'internal_ratio']].mean()
plt.stackplot(financing_ratios.index, 
              financing_ratios['debt_ratio'], 
              financing_ratios['equity_ratio'],
              financing_ratios['internal_ratio'],
              labels=['债务融资', '股权融资', '内源融资'],
              alpha=0.7)
plt.axvline(x=2015, color='k', linestyle='--', label='2015年政策变更')
plt.xlabel('年份', fontproperties=chinese_font)
plt.ylabel('比例', fontproperties=chinese_font)
plt.title('企业融资结构演变 (2011-2020)', fontproperties=chinese_font)
plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), ncol=4, prop=chinese_font)
plt.tight_layout()
plt.savefig('figures/fig2_financing_structure.png', dpi=300)

# 3. 不同企业特征的债务融资差异
plt.figure(figsize=(12, 8))

# 创建子图
fig, axes = plt.subplots(1, 3, figsize=(18, 6))

# 所有制差异
sns.boxplot(x='year', y='debt_ratio', hue='soe', data=df, ax=axes[0])
axes[0].set_title('按所有制的债务融资', fontproperties=chinese_font)
axes[0].set_xlabel('年份', fontproperties=chinese_font)
axes[0].set_ylabel('债务比率', fontproperties=chinese_font)
axes[0].legend(['民营企业', '国有企业'], prop=chinese_font)
axes[0].tick_params(axis='x', rotation=45)

# 行业差异
sns.boxplot(x='year', y='debt_ratio', hue='hightech', data=df, ax=axes[1])
axes[1].set_title('按行业类型的债务融资', fontproperties=chinese_font)
axes[1].set_xlabel('年份', fontproperties=chinese_font)
axes[1].set_ylabel('债务比率', fontproperties=chinese_font)
axes[1].legend(['传统行业', '高新技术'], prop=chinese_font)
axes[1].tick_params(axis='x', rotation=45)

# 区域差异
sns.boxplot(x='year', y='debt_ratio', hue='eastern', data=df, ax=axes[2])
axes[2].set_title('按区域的债务融资', fontproperties=chinese_font)
axes[2].set_xlabel('年份', fontproperties=chinese_font)
axes[2].set_ylabel('债务比率', fontproperties=chinese_font)
axes[2].legend(['中西部', '东部'], prop=chinese_font)
axes[2].tick_params(axis='x', rotation=45)

plt.tight_layout()
plt.savefig('figures/fig3_debt_heterogeneity.png', dpi=300)

# 4. 银行处罚与融资选择的关系
plt.figure(figsize=(15, 5))

# 创建子图
fig, axes = plt.subplots(1, 3, figsize=(18, 6))

# 债务融资与银行处罚
sns.regplot(x='lagged_penalty', y='debt_ratio', data=df, ax=axes[0], scatter_kws={'alpha':0.3}, line_kws={'color':'red'})
axes[0].set_title('银行处罚与债务融资', fontproperties=chinese_font)
axes[0].set_xlabel('滞后银行处罚', fontproperties=chinese_font)
axes[0].set_ylabel('债务比率', fontproperties=chinese_font)

# 股权融资与银行处罚
sns.regplot(x='lagged_penalty', y='equity_ratio', data=df, ax=axes[1], scatter_kws={'alpha':0.3}, line_kws={'color':'blue'})
axes[1].set_title('银行处罚与股权融资', fontproperties=chinese_font)
axes[1].set_xlabel('滞后银行处罚', fontproperties=chinese_font)
axes[1].set_ylabel('股权比率', fontproperties=chinese_font)

# 内源融资与银行处罚
sns.regplot(x='lagged_penalty', y='internal_ratio', data=df, ax=axes[2], scatter_kws={'alpha':0.3}, line_kws={'color':'green'})
axes[2].set_title('银行处罚与内源融资', fontproperties=chinese_font)
axes[2].set_xlabel('滞后银行处罚', fontproperties=chinese_font)
axes[2].set_ylabel('内源比率', fontproperties=chinese_font)

plt.tight_layout()
plt.savefig('figures/fig4_penalty_financing_relationship.png', dpi=300)

# 5. 双重差分分析可视化
plt.figure(figsize=(10, 6))

# 计算处理组和对照组的平均债务比率
did_data = df.groupby(['treated', 'year'])['debt_ratio'].mean().reset_index()
treated_data = did_data[did_data['treated'] == 1]
control_data = did_data[did_data['treated'] == 0]

plt.plot(treated_data['year'], treated_data['debt_ratio'], 'b-', marker='o', linewidth=2, label='处理组')
plt.plot(control_data['year'], control_data['debt_ratio'], 'r--', marker='s', linewidth=2, label='对照组')
plt.axvline(x=2015, color='k', linestyle='-', alpha=0.5, label='政策实施')
plt.xlabel('年份', fontproperties=chinese_font)
plt.ylabel('平均债务融资比率', fontproperties=chinese_font)
plt.title('双重差分分析：2015年政策变更对债务融资的影响', fontproperties=chinese_font)
plt.legend(prop=chinese_font)
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('figures/fig5_did_analysis.png', dpi=300)

# 6. 异质性效应可视化
plt.figure(figsize=(12, 8))

# 准备系数图表数据
hetero_data = {
    'Group': ['国有企业', '民营企业', '高新技术', '传统企业', '东部地区', '中西部地区'],
    'Debt Coefficient': [-0.039, -0.112, -0.058, -0.092, -0.061, -0.105],
    'Equity Coefficient': [0.021, 0.098, 0.083, 0.042, 0.076, 0.037],
    'Color': ['blue', 'blue', 'green', 'green', 'orange', 'orange']
}
hetero_df = pd.DataFrame(hetero_data)

# 创建系数图
fig, ax = plt.subplots(figsize=(10, 6))

# 债务融资系数条形图
ax.barh(hetero_df['Group'], hetero_df['Debt Coefficient'], height=0.4, color=hetero_df['Color'], alpha=0.6, label='债务融资')

# 股权融资系数条形图
ax.barh([g + 0.4 for g in range(len(hetero_df))], hetero_df['Equity Coefficient'], height=0.4, color=hetero_df['Color'], alpha=0.3, label='股权融资')

# 添加垂直线 x=0
ax.axvline(x=0, color='k', linestyle='-', alpha=0.3)

# 添加标签和标题
ax.set_yticks([g + 0.2 for g in range(len(hetero_df))])
ax.set_yticklabels(hetero_df['Group'], fontproperties=chinese_font)
ax.set_xlabel('系数大小', fontproperties=chinese_font)
ax.set_title('银行处罚对融资选择的异质性影响', fontproperties=chinese_font)
ax.legend(prop=chinese_font)

# 添加显著性星号
for i, group in enumerate(hetero_df['Group']):
    # 债务系数显著性标记
    if group in ['民营企业', '传统企业', '中西部地区']:
        ax.text(hetero_df['Debt Coefficient'][i] - 0.01, i, '***', ha='right', va='center', color='black')
    elif group in ['高新技术', '东部地区']:
        ax.text(hetero_df['Debt Coefficient'][i] - 0.01, i, '*', ha='right', va='center', color='black')
    
    # 股权系数显著性标记
    if group in ['民营企业']:
        ax.text(hetero_df['Equity Coefficient'][i] + 0.01, i + 0.4, '***', ha='left', va='center', color='black')
    elif group in ['高新技术', '东部地区']:
        ax.text(hetero_df['Equity Coefficient'][i] + 0.01, i + 0.4, '**', ha='left', va='center', color='black')

plt.tight_layout()
plt.savefig('figures/fig6_heterogeneity_effects.png', dpi=300)

print("数据分析和可视化完成！") 